//
//  PEMDailyExerciseController.swift
//  RelationshipIntegration
//
//  Created by iOS-Czz on 2023/11/16.
//

import UIKit
import BRPickerView
class PEMDailyExerciseController: PEMBaseViewController {
    @IBOutlet var tableView: UITableView!
    
    lazy var recordViewModel: PEMChallengeViewModel = {
        return PEMChallengeViewModel()
    }()
    lazy var viewModel: PEMDailyExerciseViewModel = {
        return PEMDailyExerciseViewModel()
    }()
    lazy var headerView: PEMDailyExerciseHeaderView = {
        let view:PEMDailyExerciseHeaderView = Bundle.main.loadNibNamed("PEMDailyExerciseHeaderView", owner: self)?.first as! PEMDailyExerciseHeaderView
        view.chooseTypeBlock = { [self] type,day in
            self.getPageData(type,day)
        }
       
        return view
    }()
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        getPageData(-1,Date().toString(format: "yyyy.MM.dd"))
    }
    override func viewDidLoad() {
        super.viewDidLoad()
        setTableView()
       
        let notificationName = Notification.Name("StandardStepSetting")
        let notificationCenter = NotificationCenter.default
        // 添加观察者
        notificationCenter.addObserver(self, selector: #selector(handleNotification(_:)), name: notificationName, object: nil)
    }
    // 处理通知的方法
    @objc func handleNotification(_ notification: Notification) {
        let defaultStep = UserDefaults.standard.value(forKey: "DefaultSteps")
        self.headerView.progressView.progress = self.viewModel.step / (defaultStep as? Double ?? 1.0) > 1 ? 1:self.viewModel.step / (defaultStep as? Double ?? 1.0)
        self.headerView.stepLabel.text = String(format: "%.0f/%.0f", self.viewModel.step, defaultStep as? Double ?? 0.0)
    }

    deinit {
        let notificationName = Notification.Name("StandardStepSetting")
        NotificationCenter.default.removeObserver(self, name: notificationName, object: nil)
    }
    func setTableView(){
        let view = UIView(frame: CGRect(x: 0, y: 0, width: Screen_Width, height: 438))
        view.addSubview(self.headerView)
        self.headerView.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }
        self.tableView.tableHeaderView = view
        self.tableView.dataSource = self
        self.tableView.delegate = self
        self.tableView.register(UINib(nibName: "PEMDailyExerciseCell", bundle: .main), forCellReuseIdentifier: "PEMDailyExerciseCell")
        self.tableView.register(UINib(nibName: "PEMEmptyCell", bundle: .main), forCellReuseIdentifier: "PEMEmptyCell")
        
    }
    func getPageData(_ type:Int,_ day:String){
//        self.recordViewModel.loadData( onSuccess: {  models in
//            let model = models.first
//        })
        self.viewModel.loadData(type,day, onSuccess: {  models in
            self.tableView.reloadData()
        })
        self.viewModel.loadAllData(day) {[self] models in
            self.headerView.distanceLabel.text = String(format: "%.2fkm",self.viewModel.distanceAll)
            self.headerView.energyLabel.text = String(format: "%.0fkcal",self.viewModel.engery)
            if let formattedTime = formatHoursToHHmmss(hours: self.viewModel.duration) {
                self.headerView.durationLabel.text = formattedTime
            }
            let defaultStep = UserDefaults.standard.value(forKey: "DefaultSteps")
            self.headerView.progressView.progress = self.viewModel.step / (defaultStep as? Double ?? 1.0)
            self.headerView.stepLabel.text = String(format: "%.0f/%.0f", self.viewModel.step, defaultStep as? Double ?? 0.0)
        }
        self.recordViewModel.loadData(day) { models in
            self.headerView.reloadData(models)
        }
    }
    func formatHoursToHHmmss(hours: Double) -> String? {
        let totalSeconds = Int(hours * 3600)
        let hoursComponent = totalSeconds / 3600
        let minutesComponent = (totalSeconds % 3600) / 60
        let secondsComponent = totalSeconds % 60

        return String(format: "%02d:%02d:%02d", hoursComponent, minutesComponent, secondsComponent)
    }

    @IBAction func gotoNutritionalRecord(_ sender: UIButton) {
        let titleArray = ["2020年02月","2020年03月","2020年04月","2020年05月"]
        let menu = DropDownMenuView.pullDropDrownMenu(anchorView: sender, titleArray: titleArray)
        menu.selectionAction = { (index: Index, str: String) -> (Void) in
            let str = "\(index)" + " " + str
            print(str)
        }
//        self.navigationController?.pushViewController(PEMSelectiveRecordController(), animated: true)
    }

}
extension PEMDailyExerciseController:UITableViewDataSource,UITableViewDelegate {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.viewModel.dataSource.count > 0 ? self.viewModel.dataSource.count:1
    }
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        if self.viewModel.dataSource.count > 0 {
            let cell:PEMDailyExerciseCell = tableView.dequeueReusableCell(withIdentifier: "PEMDailyExerciseCell") as! PEMDailyExerciseCell
            cell.model = self.viewModel.dataSource[indexPath.row]
            return cell
        }else{
            let cell:PEMEmptyCell = tableView.dequeueReusableCell(withIdentifier: "PEMEmptyCell") as! PEMEmptyCell
            return cell
        }
    }
}
